import 'package:enjoy_plus/utils/toast.dart';
import 'package:flutter/foundation.dart';
import 'package:geolocator/geolocator.dart';

/// 位置服务工具类
class LocationUtil {
  /// 私有构造函数，防止实例化
  LocationUtil._();

  /// 获取位置设置
  static LocationSettings _getLocationSettings() {
    if (defaultTargetPlatform == TargetPlatform.android) {
      return AndroidSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        forceLocationManager: true,
        intervalDuration: const Duration(seconds: 10),
        foregroundNotificationConfig: const ForegroundNotificationConfig(
          notificationText:
              "Example app will continue to receive your location even when you aren't using it",
          notificationTitle: "Running in Background",
          enableWakeLock: true,
        ),
      );
    }

    if (defaultTargetPlatform == TargetPlatform.iOS ||
        defaultTargetPlatform == TargetPlatform.macOS) {
      return AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.fitness,
        distanceFilter: 100,
        pauseLocationUpdatesAutomatically: true,
        showBackgroundLocationIndicator: false,
      );
    }

    if (kIsWeb) {
      return WebSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        maximumAge: const Duration(minutes: 5),
      );
    }

    return const LocationSettings(
      accuracy: LocationAccuracy.high,
      distanceFilter: 100,
    );
  }

  /// 获取当前位置
  static Future<Position?> getCurrentLocation() async {
    try {
      final position = await Geolocator.getCurrentPosition(
        locationSettings: _getLocationSettings(),
      );
      return position;
    } catch (e) {
      print('获取位置失败: ${e.toString()}');
      return null;
    }
  }

  /// 检查位置权限
  static Future<bool> checkLocationPermission() async {
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      ToastUtil.showError('请开启位置服务');
      return false;
    }

    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        ToastUtil.showError('位置权限被拒绝');
        return false;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      ToastUtil.showError('位置权限被永久拒绝，请在设置中开启');
      return false;
    }

    return true;
  }
}
